package com.heima.estatemanagement.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.heima.estatemanagement.dao.CommunityMapper;
import com.heima.estatemanagement.domain.Community;
import com.heima.estatemanagement.service.CommunityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.util.StringUtil;

import java.util.List;
import java.util.Map;

@Service
public class CommunityServiceImpl implements CommunityService {

    @Autowired
    private CommunityMapper communityMapper;

    public List<Community> findAll() {
        List<Community> allList = communityMapper.selectAll();
        return allList;
    }

    // 查询
    public Page<Community>  search(Map searchMap) {
        // 通过Mapper多条件查询，标准写法
        Example example = new Example(Community.class);// 指定查询的表
        //1.初始化分页条件
        int pageNum = 1;
        int pageSize = 2;
        if (searchMap != null) {
            Example.Criteria criteria = example.createCriteria();// 创建查询条件
            // 时间区间 StringUtil.isNotEmpty判空
            // andGreaterThanOrEqualTo是用于在查询条件中添加一个 “大于或等于” 的过滤条件,and是连接
            if (StringUtil.isNotEmpty((String) searchMap.get("startTime"))) {
                criteria.andGreaterThanOrEqualTo("createTime", searchMap.get("startTime"));
            }
            if (StringUtil.isNotEmpty((String) searchMap.get("endTime"))) {
                criteria.andGreaterThanOrEqualTo("updateTime", searchMap.get("endTime"));
            }
            // 名称模糊查询
            if (StringUtil.isNotEmpty((String) searchMap.get("name"))) {
                criteria.andLike("name", "%" + (String) searchMap.get("name") + "%");
            }
            // 分页
            if (searchMap.get("pageNum") != null) {
                pageNum = (Integer) searchMap.get(pageNum);
            }
            if (searchMap.get("pageSize") != null) {
                pageSize = (Integer) searchMap.get(pageSize);
            }

            // 使用PageHelper插件完成分页
            PageHelper.startPage(pageNum, pageSize);
            Page<Community> communities = (Page<Community>) communityMapper.selectByExample(example);
            return communities;
        }
        return null;
    }
}
